package com.fs.web.yz.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fs.common.pojo.CheckDetail;
import com.fs.common.pojo.CheckNote;
import com.fs.common.pojo.Order;
import com.fs.common.service.CheckNoteService;
import com.fs.common.service.UserService;
import com.fs.common.utils.ConstitutionAlgorithmUtils;
import com.fs.common.utils.ThreadPoolUtils;
import com.fs.common.yzMapper.OrderMapper;
import com.fs.web.yz.service.ICheckRecipesService;
import com.fs.web.yz.utils.CreateCheckRecipesThread;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/sdk/api/data")
public class SdkController {
    @Getter @Setter
    @Value("${img.path}")
    private String imgPath;

    @Getter @Setter
    @Value("${check.advise}")
    private String checkAdvise;

    @Autowired
    private CheckNoteService checkNoteService;

    @Autowired
    private ICheckRecipesService checkRecipesService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderMapper orderMapper;

    @ResponseBody
    @RequestMapping("/JianceList")
    public JSONObject getCheckNote(@RequestParam Map params){
        JSONObject rtn = new JSONObject();
        rtn.put("success", true);
        CheckNote check = new CheckNote();
        QueryWrapper<CheckNote> query = new QueryWrapper<>();
        query.eq("check_status", CheckNote.WAIT_CHECK);
        CheckNote result = check.selectOne(query);
        if (result != null) {
            rtn.put("tijianId", result.getCheckId());
            int feeInt = 100;
            Order order = getOrder(result.getCreaterId());
            if (order != null) {
                feeInt = order.getTotalFee();
            }
            double feeD = Double.valueOf(feeInt);
            //分转元
            rtn.put("money", ""+(feeD/100));
            String recordJson = result.getCheckJson();
            if (StringUtils.isBlank(recordJson)) {
                QueryWrapper<CheckDetail> detailQuery = new QueryWrapper<>();
                detailQuery.eq("check_id", result.getCheckId());
                CheckDetail ck = new CheckDetail();
                List<CheckDetail> detailList = ck.selectList(detailQuery);
                JSONArray detailData = new JSONArray();
                for (CheckDetail detail : detailList) {
                    JSONObject json = new JSONObject();
                    json.put("jcStatus", "" + detail.getSdkResult());
                    json.put("sdkStatus", "" + detail.getSdkStatus());
                    json.put("mediaId", detail.getDetailId());
                    json.put("mediaAddress", "-1".equals(detail.getCheckImg()) ? "" : imgPath + detail.getCheckImg());
                    json.put("type", "" + detail.getCheckType());
                    json.put("result", detail.getCheckWords());
                    detailData.add(json);
                }
                JSONObject record = new JSONObject();
                record.put("tijian_data", detailData);
                result.setCheckJson(record.toJSONString());
                recordJson = result.getCheckJson();
            }
            result.setCheckStatus(CheckNote.CHECKING);
            result.updateById();
            rtn.put("recordJson", recordJson);
        }else{
            rtn.put("tijianId", "");
            rtn.put("money", "");
            rtn.put("recordJson", "");
        }
        return rtn;
    }

    @ResponseBody
    @RequestMapping("/updateJiance")
    public JSONObject updateCheckNote(@RequestParam Map params){
        JSONObject rtn = new JSONObject();
        rtn.put("success", false);
        String tijianId = (String)params.get("tijianId");
        //诊断json回执
        String recordJson = (String)params.get("recordJson");
        //诊断结果
        String recordContent = (String)params.get("recordContent");
        //0面失败 1舌失败 2全失败 3成功
        String jcStatus = (String)params.get("jcStatus");

        if (log.isInfoEnabled()){
            log.info(String.format("%s-recordJson:%s", tijianId, recordJson));
            log.info(String.format("%s-recordContent:%s", tijianId, recordContent));
            log.info(String.format("%s-jcStatus:%s", tijianId, jcStatus));
        }
        if(StringUtils.isNotBlank(tijianId) && StringUtils.isNotBlank(recordContent)
                && StringUtils.isNotBlank(recordJson)) {
            CheckNote check = new CheckNote();
            CheckNote result = check.selectById(tijianId);
            if (result !=null) {
                result.setCheckWords(recordContent);
                result.setCheckStatus(CheckNote.CHECKED);
                result.setCheckResult(Integer.parseInt(jcStatus));

                //只有在全部成功是才开启算法生成菜单
                if(jcStatus.equals("3")){
                    //计算体质及分数
                    JSONObject record = JSONObject.parseObject(recordJson);
                    JSONArray checkData = record.getJSONArray("tijian_data");
                    for (int i = 0, l = checkData.size(); i < l; i++) {
                        JSONObject item = checkData.getJSONObject(i);
                        String type = item.getString("type");
                        if ("1,2".contains(type)) {
                            CheckDetail ck = new CheckDetail();
                            ck = ck.selectById(type + tijianId);
                            ck.setSdkResult(item.getInteger("jcStatus"));
                            ck.setSdkStatus(item.getInteger("sdkStatus"));
                            ck.setCheckWords(item.getString("result"));
                            ck.updateById();
                        }
                    }
                    JSONObject score = ConstitutionAlgorithmUtils.getMedicalResult(recordContent);
                    //添加宜吃与忌口
                    String resultContent = score.getString("resultContent");
                    Map<String, String> a3food = checkNoteService.getAdviseAndAvoid(resultContent, checkAdvise);
                    if (a3food != null) {
                        score.putAll(a3food);
                    }
                    record.put("score", score);

                    result.setCheckJson(record.toJSONString());
                    result.setCheckScore(score.toJSONString());
                    if (log.isInfoEnabled()){
                        log.info(String.format("%s-score:%s", tijianId, score.toJSONString()));
                    }
                    //可检查次数减1
                    userService.deductionCount(result.getCreaterId());
                    //检查记录与订单记录绑定
                    Order order = getOrder(result.getCreaterId());
                    if (order != null) {
                        //id绑定
                        order.setCheckId(tijianId);
                        //订单名称修改
                        order.setOrderName(getNewOrderName(order, result));
                        orderMapper.updateById(order);
                    }
                    //启动线程 生成菜谱
                    ThreadPoolUtils.execute(new CreateCheckRecipesThread(checkRecipesService, result));
                }
                result.updateById();
                rtn.put("success", true);
            }
            //
        }else{
            rtn.put("success", false);
        }
        return rtn;
    }

    /**
     * 获取最近一次支付者没有绑定检查的订单记录
     * @param createrId
     * @return
     */
    private Order getOrder(String createrId){
        QueryWrapper<Order> orderQuery = new QueryWrapper<>();
        orderQuery.isNull("check_id");
        orderQuery.eq("creater_id", createrId);
        //支付成功的订单
        orderQuery.eq("order_status", "SUCCESS");
        //单次支付订单
        orderQuery.eq("order_type", 0);
        orderQuery.orderByDesc("create_time");
        List<Order> orderList = orderMapper.selectList(orderQuery);
        Order order = null;
        if (CollectionUtils.isNotEmpty(orderList)){
            order = orderList.get(0);
        }
        return order;
    }

    /**
     * 检查记录基本信息追加到订单名称
     * @param order
     * @param cn
     * @return
     */
    private String getNewOrderName(Order order, CheckNote cn){
        String orderNameFmt = "%s(%s:%s:%s-%s)";
        String oldOrderName = order.getOrderName();
        String maternalName = cn.getMaternalName();
        String deliveryDay = DateFormatUtils.format(cn.getDeliveryDay(), "yyyyMMdd");
        String[] deliveryTypeArr = {"顺产", "剖腹产"};
        String deliveryType = deliveryTypeArr[cn.getDeliveryType()];
        String createTime = DateFormatUtils.format(cn.getCreateTime(), "yyyyMMddHHmmss");
        return String.format(orderNameFmt, oldOrderName, maternalName, deliveryDay, deliveryType, createTime);

    }
}
